package com.liz.springCloudAlibaba.consumer;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.csp.sentinel.util.StringUtil;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;


@Component
public class CustomizeBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, BlockException e) throws Exception {
        String message = "";
        int statusCode= 429;
        response.setStatus(statusCode);
        response.setContentType("application/json;charset=UTF-8");
        StringBuffer url = request.getRequestURL();
        if ("GET".equals(request.getMethod()) && StringUtil.isNotBlank(request.getQueryString())) {
            url.append("?").append(request.getQueryString());
        }
        if(e instanceof FlowException){
            message = "限流异常";
        }else if(e instanceof DegradeException){
            message = "降级异常";
        }else if(e instanceof ParamFlowException){
            message = "参数限流异常";
        }else if(e instanceof SystemBlockException){
            message = "系统负载异常";
        }else if(e instanceof AuthorityException){
            message = "授权异常";
        }
        PrintWriter out = response.getWriter();

        out.print("{\""+"statusCode\":"+statusCode+",\"message\":\""+message+"\"}");
        out.flush();
        out.close();
    }
}
